package com.onemore.task;

import java.io.File;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.voovan.db.CallType;
import org.voovan.db.JdbcOperate;
import org.voovan.http.server.HttpRequest;
import org.voovan.http.server.HttpResponse;
import org.voovan.test.db.ScriptEntity;
import org.voovan.tools.TFile;
import org.voovan.tools.TProperties;
import org.voovan.tools.log.Logger;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.fastjson.JSONObject;

/**
 * 数据库静态基类
 * @author zzj
 *
 * Voovan Framework.
 */
public class JdbcGlobal{
	static private DruidDataSource dataSource = null;
	static private DruidDataSource wmsSource = null;
//	static private JdbcOperate jOperate;
	protected final static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	static public JdbcOperate getJdbcOperate() {
		if(dataSource == null) {
			initDB();
		}
		return new JdbcOperate(dataSource);
	}
	static public JdbcOperate getWmsOperate() {
		if(wmsSource == null) {
			initDBWMS();
		}
		return new JdbcOperate(wmsSource);
	}
	static public String getArrayToString(String[] array)
	{
		String str = "";
		int i=0;
		for(i=0;i<array.length-1;i++) {
			str+=array[i]+",";
		}
		str+=array[i];
		return str;
	}
	/**
	 * 根据条件删除数据
	 * @param table
	 * @param filter
	 * @return
	 * @throws SQLException
	 */
	static public boolean delete(String table,String filter) throws SQLException
	{//SET NOCOUNT ON;
		String sql = "delete from "+table+" where "+filter;
        Map<String, Object> map = null;
		Logger.debug(sql);
		getJdbcOperate().update(sql);
		return true;
	}
	static public boolean updateDate(String table,String filter,String updateStr) throws SQLException
	{//SET NOCOUNT ON;
		String sql = "update "+table+" set "+updateStr+" where "+filter;
        Map<String, Object> map = null;
		Logger.debug(sql);
		getJdbcOperate().update(sql);
		return true;
	}
	/**
	 * 根据条件搜索数据是否存在
	 * @param table
	 * @param filter
	 * @return
	 * @throws SQLException
	 */
	static public boolean search(String table,String filter) throws SQLException
	{//SET NOCOUNT ON;
		String sql = "select count(*) as ct from "+table+" where "+filter;
        Map<String, Object> map = null;
		Logger.debug(sql);
		map = getJdbcOperate().queryMap(sql);
		return ((Integer)map.get("ct"))>0;
	}

	static public int getCount(String table,String filter) throws SQLException
	{//SET NOCOUNT ON;
		String sql = "select count(*) as ct from "+table+" where "+filter;
        Map<String, Object> map = null;
		Logger.debug(sql);
		map = getJdbcOperate().queryMap(sql);
		return (Integer)map.get("ct");
	}
	/** 
     * 判断表结构是否存在 
     * @param tableName  所判断的表名 
     * @return 
     */  
    public static boolean validateTableExist(String tableName){  
        //定义一个变量标示  
          boolean flag = true ;  
          //一个查询该表所有的语句。  
          String sql = "SELECT COUNT(*) FROM "+ tableName;  
          //获取连接  
          try{  
        	  Map<String, Object> rs = getJdbcOperate().queryMap(sql);  
             flag =  false;  
          }catch(Exception e){  
              //该表不存在，则 会跳入catch中  
              //e.printStackTrace();  
        	  Logger.info(tableName+"不存在，将自动生成");
          }
          return flag;  
     }  
	/**
	 * 初始化数据库
	 */
	static public void initDB(){
        try {
            String druidpath = TFile.getSystemPath("conf" + File.separator + "datasource.properties");
            Properties druidProperites = TProperties.getProperties(new File(druidpath));
            //Logger.info(druidProperites);
            dataSource = (DruidDataSource)DruidDataSourceFactory.createDataSource(druidProperites);
            dataSource.init();
            Logger.debug("Database connection pool init finished");
        } catch (Exception e) {
            Logger.error(e);
        }
    }
	/**
	 * 初始化数据库
	 */
	static public void initDBWMS(){
        try {
            String druidpath = TFile.getSystemPath("conf" + File.separator + "wmssource.properties");
            Properties druidProperites = TProperties.getProperties(new File(druidpath));
            //Logger.info(druidProperites);
            wmsSource = (DruidDataSource)DruidDataSourceFactory.createDataSource(druidProperites);
            wmsSource.init();
            Logger.debug("Database connection pool init finished");
        } catch (Exception e) {
            Logger.error(e);
        }
    }

	public static void setDefault(JSONObject json,String key,Object val)
	{
		if(!json.containsKey(key)) {
			json.put(key, val);
		}
	}
}
